package com.zh.freechat.infrastructure;

import com.zh.freechat.domain.auth.JwtService;
import com.zh.freechat.domain.auth.LoginUser;
import com.zh.webcommon.common.support.SpringContextHolder;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;

/**
 * 登录用户认证服务
 *
 * @author ZH
 * @date 22:31 2021/5/12
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public final class LoginAuthenticationApi {
    /**
     * 解析token，返回登录用户信息
     *
     * @param token 访问token
     * @return userInfo
     */
    public static LoginUser verifyToken(String token) throws BadCredentialsException {
        try {
            JwtService jwtService = SpringContextHolder.getBean(JwtService.class);
            return jwtService.parseJwtToken(token);
        } catch (ExpiredJwtException ex) {
            log.warn("access_token 过期");
            throw new BadCredentialsException("expired_token");
        } catch (Exception ex) {
            log.warn("access_token 无效, {}", ex.getMessage());
            throw new BadCredentialsException("invalid_token");
        }
    }

}
